package com.good.child.widgets.editext;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import androidx.appcompat.content.res.AppCompatResources;

import com.good.child.R;

/**
 * Create on: 2024/2/27
 * by Mr.Zhu
 * Description: TODO
 */
public class InputEditView extends LinearLayout {
    private TextView tvTitle;
    private XEditText etContent;
    private ImageView ivRight;
    private boolean showDelete;
    // 是否启用二维码扫描
    private boolean enableScan;

    public InputEditView(Context context) {
        super(context);
        init(null);
    }

    public InputEditView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public InputEditView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        if (attrs != null) {
            TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.InputEditView);
            //新版显示一行
            boolean showOneLineStyle = typedArray.getBoolean(R.styleable.InputEditView_oneLineStyle, false);

            if (showOneLineStyle) {
                setOrientation(HORIZONTAL);
                View.inflate(getContext(), R.layout.common_input_edit_oneline, this);
            } else {
                setOrientation(VERTICAL);
                View.inflate(getContext(), R.layout.common_input_edit, this);
            }
            tvTitle = findViewById(R.id.tv_title);
            ivRight = findViewById(R.id.iv_right);
            etContent = findViewById(R.id.et_content);
            setEnabled(true);
            int color = typedArray.getColor(R.styleable.InputEditView_bgColor, -1);
            if (color != -1)
                setBackgroundColor(color);
            Drawable drawable = typedArray.getDrawable(R.styleable.InputEditView_bgDrawable);
            if (drawable != null)
                setBackground(drawable);
            String digits = typedArray.getString(R.styleable.InputEditView_inputDigits);
            if (!TextUtils.isEmpty(digits)) {
                etContent.setFilters(new InputFilter[]{DigitsKeyListener.getInstance(digits)});
            }
            etContent.setFilters(new InputFilter[]{new InputFilter.LengthFilter(typedArray.getInt(R.styleable.InputEditView_inputLength, Integer.MAX_VALUE))});
            //是否高亮焦点文字
            etContent.setFocusHightText(typedArray.getBoolean(R.styleable.InputEditView_isHighFocusText, false));
            setTitle(typedArray.getString(R.styleable.InputEditView_title));
            setContentHint(typedArray.getString(R.styleable.InputEditView_hint));
            setContentHintTextColor(typedArray.getColorStateList(R.styleable.InputEditView_hintColor));
            setInputType(typedArray.getInt(R.styleable.InputEditView_inputType, InputType.TYPE_CLASS_TEXT));
            setTitleColor(typedArray.getColorStateList(R.styleable.InputEditView_titleColor));
            setTitleTextSize(typedArray.getDimensionPixelSize(R.styleable.InputEditView_titleTextSize, -1));
            setContentTextSize(typedArray.getDimensionPixelSize(R.styleable.InputEditView_contentTextSize, -1));
            setTitleLeftDrawable(typedArray.getDrawable(R.styleable.InputEditView_titleLeftDrawable));
            setEnabled(typedArray.getBoolean(R.styleable.InputEditView_enabled, true));
            setTitleRightDrawable(typedArray.getDrawable(R.styleable.InputEditView_titleRightDrawable));
            boolean isInputMoney = typedArray.getBoolean(R.styleable.InputEditView_isInputMoney, false);
            int pointLeftLength = typedArray.getInt(R.styleable.InputEditView_pointLeftLength, Integer.MAX_VALUE);
            int pointRightLength = typedArray.getInt(R.styleable.InputEditView_pointRightLength, 2);
            setInputMoney(isInputMoney, pointLeftLength, pointRightLength);
            bindDeleteIcon(typedArray.getBoolean(R.styleable.InputEditView_showDeleteIcon, false));
            setEnableScan(typedArray.getBoolean(R.styleable.InputEditView_isEnableScan, false));
            int resourceId = typedArray.getResourceId(R.styleable.InputEditView_rightIcon, 0);
            if (resourceId != 0) {
                setRightIcon(AppCompatResources.getDrawable(getContext(), resourceId));
            }
            int rightEditId = typedArray.getResourceId(R.styleable.InputEditView_rightEditIcon, 0);
            if (rightEditId != 0) {
                setEditRightIcon(AppCompatResources.getDrawable(getContext(), rightEditId));
            }
            resourceId = typedArray.getResourceId(R.styleable.InputEditView_leftIcon, 0);
            if (resourceId != 0) {
                setLeftIcon(AppCompatResources.getDrawable(getContext(), resourceId));
            }
            boolean hideBottomLine = typedArray.getBoolean(R.styleable.InputEditView_hideBottomLine, false);
            if (hideBottomLine) {
                setInputBg(null);
            }
            typedArray.recycle();
        } else {
            View.inflate(getContext(), R.layout.common_input_edit, this);
            tvTitle = findViewById(R.id.tv_title);
            ivRight = findViewById(R.id.iv_right);
            etContent = findViewById(R.id.et_content);
            setEnabled(true);
        }
    }

    public void setInputBg(Drawable drawable) {
        etContent.setBackground(drawable);
    }

    private Drawable[] boundsDrawable;

    private void bindDeleteIcon(boolean showDelete) {
        this.showDelete = showDelete;
        if (showDelete) {
            etContent.setDrawableRightListener(new XEditText.DrawableRightListener() {
                @Override
                public boolean onDrawableRightClick(View view) {
                    boolean intercept = etContent.getText().length() != 0;
                    etContent.setText("");
                    return intercept;
                }
            });
            etContent.addTextChangedListener(new TextWatchAdapter() {
                @Override
                public void afterTextChanged(Editable s) {
                    if (boundsDrawable == null) {
                        boundsDrawable = etContent.getCompoundDrawables();
                    }
                    if (isShowDelete()) {
                        if (s.length() > 0) {
                            etContent.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.login_delete, 0);
                        } else {
                            etContent.setCompoundDrawablesWithIntrinsicBounds(boundsDrawable[0], boundsDrawable[1], boundsDrawable[2], boundsDrawable[3]);
                        }
                    }
                }
            });
        }
    }

    public boolean isShowDelete() {
        return showDelete;
    }

    public void setShowDelete(boolean showDelete) {
        this.showDelete = showDelete;
    }

    public boolean isEnableScan() {
        return enableScan;
    }

    public void setEnableScan(boolean enableScan) {
        this.enableScan = enableScan;
    }

    /**
     * 自动补充小数位
     *
     * @param s
     * @param pointer_length
     * @return
     */
    private CharSequence genDecimalStr(String s, int pointer_length) {
        if (TextUtils.isEmpty(s))
            return s;
        if (s.contains(".")) {
            //存在小数位判断，有几位
            String[] temps = s.split("\\.");
            if (temps[1].length() == pointer_length)
                return s;
            StringBuilder sb = new StringBuilder(temps[0]);
            sb.append(".");
            sb.append(temps[1]);
            for (int i = temps[1].length(); i < pointer_length; i++) {
                sb.append("0");
            }
            return sb;
        } else {
            StringBuilder sb = new StringBuilder(s).append(".");
            for (int i = 0; i < pointer_length; i++) {
                sb.append("0");
            }
            return sb;
        }
    }

    public InputEditView setInputMoney(boolean isInputMoney, int pointLeftLength, int pointRightLength) {
        if (isInputMoney) {
//            etContent.setOnFocusChangeListener(new OnFocusChangeListener() {
//                @Override
//                public void onFocusChange(View v, boolean hasFocus) {
//                    if (!hasFocus) {
//                        CharSequence charSequence = genDecimalStr(getContent().toString(), pointRightLength);
//                        etContent.setText(charSequence);
//                    }
//                }
//            });
            etContent.setPointLeftLength(pointLeftLength);
            etContent.setPointRightLength(pointRightLength);
        }
        return this;
    }


    @Override
    public void setOnClickListener(@Nullable View.OnClickListener l) {
        etContent.setOnClickListener(l);
        super.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (l != null) {
                    l.onClick(etContent);
                }
            }
        });
    }


    public InputEditView setTitle(CharSequence title) {
        tvTitle.setText(title);
        return this;
    }

    public InputEditView setTitleLeftDrawable(Drawable leftDrawable) {
        Drawable[] compoundDrawables = tvTitle.getCompoundDrawables();
        tvTitle.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, compoundDrawables[1], compoundDrawables[2], compoundDrawables[3]);
        return this;
    }

    public InputEditView setTitleRightDrawable(Drawable rightDrawable) {
        String s = tvTitle.getText().toString().trim();
        if (rightDrawable == null || TextUtils.isEmpty(s)) {
            SpannableString string = new SpannableString(s);
            tvTitle.setText(string);
        } else {
            //创建SpannableString对象
            SpannableString string = new SpannableString(s + "  ");
            //创建ImageSpan对象
            rightDrawable.setBounds(0, 0, rightDrawable.getIntrinsicWidth(), rightDrawable.getIntrinsicHeight());
            ImageSpan imageSpan = new CenterAlignImageSpan(rightDrawable);
            //给SpannableString对象设置ImageSpan
            string.setSpan(imageSpan, s.length() + 1, s.length() + 2, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            tvTitle.setText(string);
        }
        return this;
    }

    public InputEditView setTitleTextSize(float size) {
        if (size > 0) {
            tvTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
        }
        return this;
    }

    public InputEditView setTitleColor(int color) {
        tvTitle.setTextColor(color);
        return this;
    }

    public InputEditView setTitleColor(ColorStateList color) {
        if (color != null) {
            tvTitle.setTextColor(color);
        }
        return this;
    }

    public InputEditView setContent(CharSequence content) {
        etContent.setText(content);
        return this;
    }

    public InputEditView setContentHint(CharSequence content) {
        etContent.setHint(content);
        return this;
    }

    @Override
    public void setGravity(int gravity) {
        etContent.setGravity(gravity);
    }

    public InputEditView setInputType(int type) {
        etContent.setFocusable(type != 0);
        etContent.setInputType(type);
        return this;
    }

    public InputEditView setContentTextSize(float size) {
        if (size > 0) {
            etContent.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
        }
        return this;
    }

    public InputEditView setContentTextColor(int color) {
        etContent.setTextColor(color);
        return this;
    }

    public InputEditView setContentHintTextColor(int color) {
        etContent.setHintTextColor(color);
        return this;
    }

    public InputEditView setContentHintTextColor(ColorStateList color) {
        if (color != null) {
            etContent.setHintTextColor(color);
        }
        return this;
    }


    public InputEditView setLeftIcon(@DrawableRes int resId) {
        if (resId != 0) {
            etContent.setCompoundDrawablesWithIntrinsicBounds(resId, 0, 0, 0);
        }
        return this;
    }

    public InputEditView setLeftIcon(Drawable drawable) {
        if (drawable != null) {
            etContent.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
        }
        return this;
    }

    public InputEditView setRightIcon(@DrawableRes int resId) {
        if (resId != 0) {
            etContent.setCompoundDrawablesWithIntrinsicBounds(0, 0, resId, 0);
        }
        return this;
    }

    public InputEditView setRightIcon(Drawable drawable) {
        if (drawable != null) {
//            etContent.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
            ivRight.setVisibility(VISIBLE);
            ivRight.setImageDrawable(drawable);
        }
        return this;
    }

    public InputEditView hideRightIcon() {
        ivRight.setVisibility(GONE);
        return this;
    }

    public InputEditView hideEditRightIcon() {
        etContent.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        return this;
    }

    public InputEditView setEditRightIcon(Drawable drawable) {
        if (drawable != null) {
            etContent.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
        }
        return this;
    }

    public InputEditView setRightIconClickListener(View.OnClickListener onClickListener) {
        ivRight.setOnClickListener(view -> {
            if (onClickListener != null && isEnabled()) {
                onClickListener.onClick(ivRight);
            }
        });
        return this;
    }

    public InputEditView setLeftIconClickListener(View.OnClickListener onClickListener) {
        etContent.setDrawableLeftListener(view -> {
            if (onClickListener != null && isEnabled()) {
                onClickListener.onClick(etContent);
            }
            return false;
        });
        return this;
    }

    public EditText getEtContent() {
        return etContent;
    }

    public CharSequence getContent() {
        return etContent.getText();
    }

    public String getTitle() {
        return tvTitle.getText().toString();
    }

    public void setEnabled(boolean flag) {
        super.setEnabled(flag);
        getEtContent().setEnabled(flag);
    }


    public InputEditView setMaxInputLength(int maxInputLength) {
        etContent.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxInputLength)});
        return this;
    }

    public void setInputFilters(InputFilter inputFilter) {
        etContent.setFilters(new InputFilter[]{inputFilter});
    }

    public void setTextChangeListener(TextWatcher textWatcher) {
        etContent.addTextChangedListener(textWatcher);
    }
}
